/*
 * @Author: Nice-2-CU 81088875+Nice-2-CU@users.noreply.github.com
 * @Date: 2023-07-10 14:16:48
 * @LastEditors: Nice-2-CU 81088875+Nice-2-CU@users.noreply.github.com
 * @LastEditTime: 2023-07-20 08:54:19
 * @FilePath: \lost-found-management\src\permission.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import router from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import Cookies from 'js-cookie'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  let hasUserToken = Cookies.get("user")
  let userRole = Cookies.get("user_role")

  console.log(1, from)
  console.log(2, to)

  if(from.path === '/login' || from.path === '/') {
    if(to.path === '/login') {
      next()
    } else {
      if(userRole) {
        let role = JSON.parse(userRole).roleCodeList
        if(role.length === 1 && role[0] === 'user') {
          next('/login')
        } else {
          next()
        }
      } else {
        next('/login')
      }
    }
  } else {
    if(to.path === '/login') {
      if(hasUserToken) {
        next('/dashboard')
      } else {
        next()
      }
    } else {
      next()
    }
  }

  // if(userRole) {
  //   let role = JSON.stringify(userRole).roleCodeList
  //   if(role.length === 1 || role[0] === 'user') {
  //     next('/login')
  //   } else {
  //     next('/dashboard')
  //   }
  // } else {
  //   if(whiteList.indexOf(to.path) !== -1) {
  //     next()
  //   } else {
  //     next('/login')
  //   }
  // }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
